package com.wish.housing.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.wish.common.core.usconfig.common.MsgResult;
import com.wish.common.redis.service.RedisService;
import com.wish.housing.entity.Region;
import com.wish.housing.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 王泓翔-杨子强-地区表 前端控制器
 * </p>
 *
 * @author benjamin
 * @since 2022-03-28
 */
@RestController
@RequestMapping("/region")
public class RegionController {

    @Autowired
    IRegionService iRegionService;

    @Autowired
    RedisService redisService;

    @GetMapping("/regionList")
    public MsgResult regionList() {
        Boolean aBoolean = redisService.hasKey("REGION_LIST");
        if (!aBoolean) {
            List<Region> list = iRegionService.list();
            List<Tree<Integer>> build = TreeUtil.build(list, 1,
                    (region, tree) -> {
                        tree.setParentId(region.getParentId());
                        tree.setId(region.getRegionId());
                        tree.setName(region.getRegionName());
                    });
            redisService.setCacheList("REGION_LIST", build);
        }
        List<Object> region_list = redisService.getCacheList("REGION_LIST");
        return MsgResult.succeed(region_list);
    }

    @GetMapping("/getProvince")
    public MsgResult getProvince(Integer pid) {
        List<Region> list = iRegionService.getProvince(pid);
        return MsgResult.succeed(list);
    }

}
